<!--
    	作者：offline
    	时间：2018-09-22
    	描述：子账号管理
    	供应商测试账号  G100346 111111
    -->

<template>
  <div class="m-view-subAccountManager m-window" v-loading="loading">
    <div class="m-condition">
      <el-row :gutter="10">
        <el-col :span="2" :offset="6">
          <el-button type="primary" @click="query" :disabled="btnDis"
            >查询</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="add" :disabled="btn_add_Dis"
            >新增</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="edit" :disabled="btn_edit_Dis"
            >编辑</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="reuse" :disabled="btn_reuse_Dis"
            >启用</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="del" :disabled="btn_del_Dis"
            >停用</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addRole" :disabled="btn_addRole_Dis"
            >授权</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="pushSet" :disabled="btn_addRole_Dis"
            >推送设置</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button
            type="primary"
            @click="resetPwd"
            :disabled="btn_resetPwd_Dis"
            >重置密码</el-button
          >
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="openCCUser">开通CC账号</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-input
            v-model="Sup_name"
            placeholder="请输入帐号或名称"
            clearable
            @keyup.enter.native="query"
          ></el-input>
        </el-col>
        <el-col :span="3">
          <el-radio
            :disabled="radio_Disabled"
            v-model="radio"
            label="1"
            @change="changeRa"
            >显示启用</el-radio
          >
        </el-col>
        <el-col :span="3">
          <el-radio
            :disabled="radio_Disabled"
            v-model="radio"
            label="0"
            @change="changeRa"
            >显示禁用</el-radio
          >
        </el-col>
      </el-row>
    </div>

    <div class="m-agTable m-top2 m-bottom">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        rowSelection="multiple"
      ></ag-grid-vue>
    </div>
    <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page.sync="currentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <!--弹框-子账号编辑页面-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="60"
      v-dialogDrag
      :before-close="handleClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="帐号：" v-if="in_uid_show">
              <el-input v-model="ruleForm.username" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="in_uid_show">
              <el-checkbox v-model="isAdmin" disabled>管理员</el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          label="名称："
          prop="employee_name"
          :class="{ 'tip-form-item': nameTips }"
        >
          <el-input
            v-model="ruleForm.employee_name"
            clearable
            maxlength="50"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <span class="tips" v-show="nameTips">初始密码:111111</span>
        <!-- <el-form-item label="密码：" prop="password" v-if="in_password_show">
          <el-input
            v-model="ruleForm.password"
            @keyup.native="clearSpace('password')"
            placeholder="请输入6~11位的密码，如：123456"
            clearable
            maxlength="11"
            autocomplete="off"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码确认：" prop="confirmPassword" v-if="in_password2_show">
          <el-input v-model="ruleForm.confirmPassword" clearable type="password"></el-input>
				</el-form-item>-->
        <el-form-item
          label="邮箱："
          prop="email"
          :class="{ 'tip-form-item': emailTips }"
        >
          <el-input
            v-model="ruleForm.email"
            clearable
            maxlength="50"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <span class="tips" v-show="emailTips"
          >设置邮箱可用于重置密码、接收系统邮件</span
        >
        <el-form-item
          label="手机："
          prop="phone"
          :class="{ 'tip-form-item': phoneTips }"
        >
          <el-input
            v-model="ruleForm.phone"
            placeholder="请输入11位的手机号，如：13702123456"
            maxlength="11"
            clearable
          ></el-input>
        </el-form-item>
        <span class="tips" v-show="phoneTips"
          >设置手机可用于接收系统短信提醒</span
        >
        <el-form-item label="备注：" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            placeholder="(100字以内)"
            clearable
            type="textarea"
            maxlength="100"
            :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="角色：" v-if="item_role_show">
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="city in cities"
              :label="city.id"
              :key="city.id"
              :disabled="city.disabled == true"
              >{{ city.name }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>

        <el-form-item
          label="运输方: "
          prop="transport"
          v-if="showTransport && mode == 'add'"
        >
          <el-select
            v-model="ruleForm.transport"
            placeholder="运输方"
            clearable
            @change="handleChangeTransport"
            ref="transportSeleter"
          >
            <el-option
              v-for="item in transportList"
              :key="item.id"
              :label="item.transportName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="运输方："
          prop="remark"
          v-if="mode == 'edit' && ruleForm.thirdPartyName"
        >
          <el-input v-model="ruleForm.thirdPartyName" disabled></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveData" :loading="btn_loading"
          >保存</el-button
        >
      </span>
    </el-dialog>

    <!--弹框-授权页面-->
    <el-dialog
      :title="title"
      :visible.sync="addrole_Vis"
      width="60"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :model="ruleForm" ref="ruleForm" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="名称：">
              <el-input
                v-model="ruleForm.employee_name"
                autocomplete="off"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="角色：">
              <el-checkbox-group
                v-model="checkedCities"
                @change="handleCheckedCitiesChange"
              >
                <el-checkbox
                  v-for="city in cities"
                  :label="city.id"
                  :key="city.id"
                  >{{ city.name }}</el-checkbox
                >
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel2('role')">取消</el-button>
        <el-button
          type="primary"
          @click="saveRole"
          :disabled.sync="btn_saveRole_dis"
          >保存</el-button
        >
      </span>
    </el-dialog>

    <!-- 推送设置弹窗 -->
    <el-dialog
      :title="'推送设置'"
      :visible.sync="push_Vis"
      width="50%"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="m-push-dialog"
    >
      <el-form :model="ruleForm" ref="ruleForm" label-width="80px">
        <el-form-item label="账号：">
          <el-input
            v-model="ruleForm.username"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="名称：">
          <el-input
            v-model="ruleForm.employee_name"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
        <el-form-item label="手机：">
          <el-input
            v-model="ruleForm.phone"
            autocomplete="off"
            disabled
          ></el-input>
        </el-form-item>
      </el-form>
      <el-table
        :data="tableData"
        :border="true"
        size="mini"
        v-loading="tab_loading"
        max-height="200px"
      >
        <el-table-column label="推送节点" prop="busTypeName"></el-table-column>
        <el-table-column label="短信推送" align="center">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.msgPush"></el-checkbox>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel2('push')">取消</el-button>
        <el-button
          type="primary"
          @click="savePush"
          :disabled.sync="btn_saveRole_dis"
          :loading="btn_loading"
          >保存</el-button
        >
      </span>
    </el-dialog>

    <!-- 开通CC账号弹框 -->
    <el-dialog
      title="开通CC账号"
      :visible.sync="dialogCcVisible"
      width="50%"
      :before-close="handleCloseCcAccount"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleCcForm"
        :rules="rulesCc"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="CC账号：">
          <div class="m-ccAccount" style="display: flex">
            <el-input
              v-model="ruleCcForm.ccAccount"
              placeholder="请输入CC账号"
              :disabled="true"
              clearable
            ></el-input>
            <div class="m-originPassword">(初始密码:lesso2128#)</div>
          </div>
        </el-form-item>
        <el-form-item label="申请人名称：">
          <el-input
            v-model="ruleCcForm.employeeName"
            :disabled="true"
            placeholder="请输入名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="申请人手机：">
          <el-input
            v-model="ruleCcForm.mobile"
            placeholder="请输入手机号"
            :disabled="true"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="所属角色：" prop="role">
          <el-select
            placeholder="请选择角色"
            v-model="ruleCcForm.role"
            clearable
            @change="changeUserRole"
          >
            <el-option
              v-for="(item, index) in roleCcList"
              :key="index"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="CC初始名称：">
          {{ ruleCcForm.originalCCName }}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseCcAccount">取消</el-button>
        <el-button type="primary" @click="handleSaveCcAccount('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import aes from "lesso-common/public/aes.js";
import waterfall from "async-es/waterfall";
import constant from "@/public/constant.js";
import { mapMutations } from "vuex";
import gridOptions from "lesso-common/public/gridOptions";
import supplierInfo from "@/public/supplierInfo";
const rolelist_id = [];
import _utils from "@/public/utils";

export default {
  data() {
    var validatePass1 = (rule, value, callback) => {
      let regCn = new RegExp("[\\u4E00-\\u9FFF]+", "g");
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (regCn.test(value)) {
        callback(new Error("请勿输入汉字!"));
      } else {
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var checkMail = (rule, value, callback) => {
      setTimeout(() => {
        if (value) {
          var reg = new RegExp(
            "^([0-9A-Za-z-_.]+)@([0-9a-z]+.[a-z]{2,3}(.[a-z]{2})?)$"
          );
          if (!reg.test(value)) {
            this.emailTips = false;
            callback(new Error("请输入正确的邮箱地址"));
          } else this.emailTips = true;
          callback();
        } else {
          this.emailTips = true;
          callback();
        }
      }, 100);
    };
    var checkTel = (rule, value, callback) => {
      setTimeout(() => {
        if (value) {
          var reg = new RegExp(
            "^((13[0-9])|(14[0-9])|(15([0-9]))|(18[0-9]))\\d{8}$"
          );
          if (!reg.test(value)) {
            this.phoneTips = false;
            callback(new Error("请输入正确的电话号码"));
          } else this.phoneTips = true;
          callback();
        } else {
          this.phoneTips = true;
          callback();
        }
      }, 100);
    };
    var checkName = (rule, value, callback) => {
      if (!value) {
        this.nameTips = false;
        callback(new Error("请输入账户名称"));
      } else {
        if (value.length > 50) {
          this.nameTips = false;
          callback(new Error("名称最多可输入50个字符!"));
        } else {
          this.nameTips = true;
          callback();
        }
      }
    };
    // var selectTransport = (rule,value,callback)=>{
    //    if (!value || value=='') {
    //     callback(new Error('请选择运输方'));
    //   }else{
    //     callback();
    //   }
    // }
    return {
      btnDis: true,
      isFirst: true,
      Sup_name: "",
      radio: "1",
      columnDefs: [],
      rowData: [],
      loading: false,
      btn_loading: false,
      radio_Disabled: false,
      btn_add_Dis: false, //新增子账号
      btn_edit_Dis: false, //修改权限
      btn_reuse_Dis: true,
      btn_del_Dis: false,
      btn_addRole_Dis: false, //添加权限
      btn_resetPwd_Dis: false,

      //子账号-弹出框
      mode: "",
      title: "",
      dialogVisible: false, //子账号新增、编辑页面
      item_role_show: false, //角色勾选
      ruleForm: {
        username: "",
        employee_name: "",
        password: "",
        confirmPassword: "",
        email: "",
        phone: "",
        remark: "",
        transport: "",
      },
      isAdmin: false,
      in_uid_show: false,
      in_password_show: false,
      in_password2_show: true,
      inputDis: false,
      disState: false,
      btnShow: true,
      rules: {
        employee_name: [
          {
            required: true,
            trigger: ["blur", "change"],
            validator: checkName,
          },
        ],
        password: [
          {
            required: true,
            validator: validatePass1,
            trigger: ["blur", "change"],
          },
          {
            min: 6,
            max: 11,
            message: "密码长度在6-11位",
            trigger: "change",
          },
        ],
        confirmPassword: [
          {
            required: true,
            validator: validatePass2,
            trigger: "change",
          },
        ],
        remark: [
          {
            min: 0,
            max: 100,
            triggerr: "change",
            message: "长度在100个字符",
          },
        ],
        email: [
          {
            validator: checkMail,
            trigger: "change",
          },
        ],
        phone: [
          {
            validator: checkTel,
            trigger: "change",
          },
        ],
        transport: [
          {
            validator: this.selectTransport,
            trigger: "change",
            required: this.showTransport,
          },
        ],
      },

      //授权-弹出框
      addrole_Vis: false,
      checkedCities: [], //默认勾选
      cities: [],
      btn_saveRole_dis: false,
      currentPage: 1,
      pageSize: 30,
      total: 0,
      current: 1,
      emailTips: true,
      phoneTips: true,
      nameTips: true,
      // 推送设置弹窗
      push_Vis: false,
      tab_loading: false,
      tableData: [],
      // 主账号
      mainAccount: "",
      showTransport: false,

      //   开通CC账号
      ruleCcForm: {
        ccAccount: "", //CC账号
        employeeName: "", //申请人名称
        mobile: "", //手机
        role: "", //角色
        originalCCName: "",
      },
      roleCcList: [], //cc 所属角色列表
      getroleName: "", //获取角色name
      dialogCcVisible: false, //CC 弹框
      rulesCc: {
        role: [{ required: true, message: "请选择角色", trigger: "change" }],
      },
    };
  },
  beforeMount() {
    this.gridOptions = Object.assign(
      {
        context: {
          componentParent: this,
        },
        rowSelection: "multiple",
        onRowSelected: (gird) => {
          let rows = gird.api.getSelectedRows();
          this.btn_resetPwd_Dis = rows.some((item) => {
            return item.isAdmin == 1;
          });
        },
        enableColResize: true,
        localeText: localeText,
      },
      gridOptions()
    );
    this.columnDefs = [
      { headerName: "accountId", field: "accountId", hide: true },
      {
        headerName: "帐号",
        field: "username",
        width: 120,
        checkboxSelection: true,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
      },
      { headerName: "名称", field: "employee_name", width: 250 },
      { headerName: "邮箱", field: "email", width: 150 },
      { headerName: "手机", field: "phone", width: 120 },
      { headerName: "管理员", field: "isAdmin", hide: true },
      { headerName: "角色组ID", field: "roleID", hide: true },
      { headerName: "角色组", field: "role", width: 160 },
      { headerName: "备注", field: "remark" },
       { headerName: "CC账号", field: "ccAccount",width: 120 },
        { headerName: "CC账号状态", field: "cc",width: 120,
         cellRenderer: (params) => {
          return params.value == 1 ? "已开通" : "未开通";
        },
        },
      { headerName: "状态", field: "state", hide: true },
    ];
  },
  mounted() {
    this.search(1);
  },
  methods: {
    ...mapMutations(["loginOut"]),
    handleSizeChange(params) {
      this.pageSize = params;
      this.current = 1;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(params) {
      this.currnet = params;
      this.currentPage = params;
      this.search();
    },
    handlePrevClick(params) {
      this.current = params;
      this.currentPage = params;
      this.search();
    },
    handleNextClick(params) {
      this.current = params;
      this.currentPage = params;
      this.search();
    },
    // 关键字搜索查询
    query(){
      this.searchKeyword = this.Sup_name.replace(/\s+/g, "");
      this.search(true)
    },
    search(flag) {
      if(flag) {
        this.currentPage = 1;
      }
      //查询
      var that = this;
      var obj = {};
      var supplier = [];
      supplier.push(constant.supplierData);
      obj.supplierCode = supplier[0].supplierCode;
      obj.name = this.searchKeyword || '';
      obj.state = this.radio;
      obj.current = this.currentPage;
      obj.size = this.pageSize;
      this.loading = true;
      this.btnDis = true;
      _Api
        .getSup_userList(obj)
        .then(function (response) {
          that.btnDis = false;
          that.loading = false;
          var data = response.data;
          if (data.code == "1") {
            if (data.total > 0) {
              //角色ID
              data.rows.forEach(function (row) {
                var roleID = "";
                row.authUserGroupUsers.forEach(function (rolelist) {
                  roleID += rolelist.userGroupId + ",";
                });
                roleID = roleID.substr(0, roleID.length - 1);
                row.roleID = roleID;
              });

              //角色名
              let orginRoleList = [];
              data.rows.forEach(function (row) {
                var role = "";
                row.authUserGroupUsers.forEach(function (rolelist) {
                  let authName = rolelist.userGroupName;
                  let roleName =
                    authName.indexOf("财务") > -1
                      ? authName.substr(9, 2)
                      : authName.substr(9, 3);
                  role += roleName + "，";

                  let obj = {};

                  obj.code = rolelist.userGroupId;
                  obj.name = roleName;
                  orginRoleList.push(obj);
                });
                that.roleCcList = that.handleRemoveArr(orginRoleList);
                console.log(that.roleCcList, "角色--名称");
                role = role.substr(0, role.length - 1);
                row.role = role;

                if (row.isAdmin == 1) {
                  that.mainAccount = row.username;
                }
              });
              that.gridOptions.api.setRowData(data.rows);
              that.total = data.total;
            } else {
              that.gridOptions.api.setRowData([]);
              that.total = 0;
              that.current = 1;
            }
          } else {
            that.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
            that.total = 0;
            that.current = 1;
          }
        })
        .catch(() => {
          that.loading = false;
          that.$alert("操作失败", {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        });
    },
    // 去重
    handleRemoveArr(arr) {
      let map = new Map();
      for (let item of arr) {
        if (!map.has(item.name)) {
          map.set(item.name, item);
        }
      }
      return [...map.values()];
    },
    // 清除前后空格符
    clearSpace(value) {
      if (this.ruleForm[value]) {
        this.ruleForm[value] = this.ruleForm[value].replace(
          /(^\s*)|(\s*$)/g,
          ""
        );
      }
    },
    add() {
      //新增
      this.title = "新增";
      this.mode = "add";
      this.ruleForm = {
        username: "",
        employee_name: "",
        password: "111111",
        confirmPassword: "",
        email: "",
        phone: "",
        remark: "",
        transport: "",
      };
      this.dialogVisible = true;
      this.in_uid_show = false;
      setTimeout(() => {
        this.in_password_show = true;
      }, 100);
      this.in_password2_show = true;
      this.item_role_show = true;
      this.disState = false;
      this.emailTips = true;
      this.phoneTips = true;
      var obj = {};
      obj.name = "";
      obj.userId = 0;
      obj.supplierCode = "";
      //获取角色的方法
      this.cities.length = 0;
      this.checkedCities.length = 0;
      var that = this;
      // this.$nextTick(()=>{
      if (!this.isFirst) {
        that.$refs["ruleForm1"].resetFields();
      }
      supplierInfo
        .getUserInfo(this.$global.user.userName)
        .then((supplierInfo) => {
          that.supplierInfo = supplierInfo[0];
          obj.supplierCode = supplierInfo[0].supplierCode;
        })
        .then(() => {
          //获取运输方
          _Api
            .getMstTransportList({ supplierCode: obj.supplierCode, flag: 0 })
            .then((req) => {
              var data = req.data;
              if (data.code == "1") {
                this.transportList = data.rows;
              }
            });

          _Api
            .getRoleList(obj)
            .then(function (response) {
              var data = response.data;
              if (data.code == "1") {
                //循环功能角色组，寻找供应商的
                for (var i = 0; i < data.rows.authUserGroups.length; i++) {
                  if (data.rows.authUserGroups[i].name.indexOf("供应商") > -1) {
                    //包含供应商
                    let authName = data.rows.authUserGroups[i].name;
                    let roleName =
                      authName.indexOf("财务") > -1
                        ? authName.substr(9, 2)
                        : authName.substr(9, 3);
                    if (roleName != "管理员") {
                      data.rows.authUserGroups[i].name = roleName;
                      that.cities.push(data.rows.authUserGroups[i]); //
                    }
                  }
                }
                for (var k = 0; k < data.rows.authUserGroupUsers.length; k++) {
                  that.checkedCities.push(
                    data.rows.authUserGroupUsers[k].userGroupId
                  );
                }
              } else {
                that.cities = [];
                that.checkedCities = [];
              }
            })
            .catch(() => {
              that.$alert("请求失败！", {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
              that.cities = [];
              that.checkedCities = [];
            });
        });

      // })

      this.isFirst = false;
    },
    edit() {
      this.isFirst = false;
      this.disState = false;
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择一个想编辑的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else if (row.length > 1) {
        this.$alert("提示：请选择一个想编辑的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        this.ruleForm = JSON.parse(JSON.stringify(row[0])); //深拷贝防止改变ruleform影响表格数据变化
        this.title = "编辑";
        this.mode = "edit";
        this.dialogVisible = true;
        this.in_uid_show = true;
        this.in_password_show = false;
        this.in_password2_show = false;
        if (row[0].isAdmin == 1) {
          this.isAdmin = true;
        } else {
          this.isAdmin = false;
        }

        this.item_role_show = false;
      }
    },
    addRole() {
      var row = this.gridOptions.api.getSelectedRows();
      var that = this;
      if (row.length <= 0) {
        this.$alert("提示：请选择一个想授权的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else if (row.length > 1) {
        this.$alert("提示：请选择一个想授权的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        this.ruleForm = row[0];
        this.title = "授权";
        if (row[0].isAdmin == 1) {
          this.isAdmin = true;
          this.$alert("不能对管理员授权", {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
          return;
        } else {
          this.isAdmin = false;
          this.addrole_Vis = true;
        }

        var obj = {};
        obj.name = "";
        obj.userId = row[0].accountId;

        this.cities.length = 0;
        this.checkedCities.length = 0;
        this.loading = true;
        _Api
          .getRoleList(obj)
          .then(function (response) {
            var data = response.data;
            that.loading = false;
            if (data.code == "1") {
              //循环功能角色组，寻找供应商的
              for (var i = 0; i < data.rows.authUserGroups.length; i++) {
                if (data.rows.authUserGroups[i].name.indexOf("供应商") > -1) {
                  //包含供应商
                  let authName = data.rows.authUserGroups[i].name;
                  let roleName =
                    authName.indexOf("财务") > -1
                      ? authName.substr(9, 2)
                      : authName.substr(9, 3);
                  // data.rows.authUserGroups[i].name = data.rows.authUserGroups[i].name.substr(9, 3);
                  // that.cities.push(data.rows.authUserGroups[i]);//
                  if (roleName != "管理员") {
                    data.rows.authUserGroups[i].name = roleName;
                    that.cities.push(data.rows.authUserGroups[i]); //
                  }
                }
              }
              for (var k = 0; k < data.rows.authUserGroupUsers.length; k++) {
                that.checkedCities.push(
                  data.rows.authUserGroupUsers[k].userGroupId
                );
              }
            } else {
              that.cities = [];
              that.checkedCities = [];
            }
          })
          .catch(() => {
            this.loading = false;
            that.$alert("请求失败！", {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
            that.cities = [];
            that.checkedCities = [];
          });
      }
    },
    del() {
      //停用
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择需要停用的帐号", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        for (var i = 0; i < row.length; i++) {
          //检查是否勾选了管理员账号
          if (row[i].isAdmin == 1) {
            this.$alert("不能停用管理员帐号！", {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
            return;
          }
          //检查是否勾选了自己的帐号
          if (row[i].accountId == this.$global.user.id) {
            this.$alert("停用帐号失败！", {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure",
            });
            return;
          }
        }

        var that = this;
        this.$confirm("是否停用帐号？", "消息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true,
        })
          .then(() => {
            var id = "";
            for (var i = 0; i < row.length; i++) {
              id += row[i].accountId + ",";
            }

            id = id.substr(0, id.length - 1);

            var obj = {
              accountId: id,
              state: 1, //停用状态
              modifyerId: this.$global.user.id, //修改人ID
              modifyer: this.$global.user.employeeName, //修改人
            };
            this.loading = true;
            _Api
              .reuseOrdel_user(obj)
              .then(function (response) {
                that.loading = false;
                var data = response.data;
                if (data.code == "1") {
                  that.$message({
                    message: "已停用",
                    type: "success",
                  });
                  that.search();
                } else {
                  that.$alert(data.info, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                }
              })
              .catch(() => {
                this.loading = false;
                that.$alert("请求失败！", {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              });
          })
          .catch(() => {});
      }
    },
    reuse() {
      //启用
      var row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择你想启用的帐号", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        var that = this;
        this.$confirm("是否启用帐号？", "消息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true,
        })
          .then(() => {
            var id = "";
            for (var i = 0; i < row.length; i++) {
              id += row[i].accountId + ",";
            }

            id = id.substr(0, id.length - 1);

            var obj = {
              accountId: id,
              state: 0, //启用状态
              modifyerId: this.$global.user.id, //修改人ID
              modifyer: this.$global.user.employeeName, //修改人
            };
            this.loading = true;
            _Api
              .reuseOrdel_user(obj)
              .then(function (response) {
                that.loading = false;
                var data = response.data;
                if (data.code == "1") {
                  that.$message({
                    message: "已启用",
                    type: "success",
                  });
                  that.search();
                } else {
                  that.$alert(data.info, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                }
              })
              .catch(() => {
                this.loading = false;
                that.$alert("请求失败！", {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              });
          })
          .catch(() => {});
      }
    },
    //显示启用或禁用
    changeRa(radio) {
      if (radio == "1") {
        //显示启用
        this.btn_add_Dis = false;
        this.btn_addRole_Dis = false;
        this.btn_resetPwd_Dis = false;
        this.btn_edit_Dis = false;
        this.btn_del_Dis = false; //停用按钮的可编辑状态
        this.btn_reuse_Dis = true; //启用按钮的可编辑状态
        this.search(1);
      } //显示禁用
      else {
        this.btn_add_Dis = true;
        this.btn_addRole_Dis = true;
        this.btn_resetPwd_Dis = true;
        this.btn_edit_Dis = true;
        this.btn_del_Dis = true; //停用按钮的可编辑状态
        this.btn_reuse_Dis = false; //启用按钮的可编辑状态
        this.search(1);
      }
    },
    cancel() {
      this.ruleForm = {};
      this.$refs["ruleForm1"].clearValidate();
      this.dialogVisible = false;
    },
    saveData() {
      //保存
      if (this.mode == "add") {
        //新增帐号
        this.$refs["ruleForm1"].validate((valid) => {
          if (valid == false) {
            return false;
          }
          this.disState = true;
          //			        	var supplier = JSON.parse(localStorage.getItem("supplier"));
          var supplier = [];
          supplier.push(constant.supplierData);
          var that = this;
          //获取秘钥
          var obj2 = {};
          obj2.tokenkey = "get";
          _Api.accountRegister(obj2).then(function (response) {
            var data = response.data;
            if (data.meta.code == "200") {
              //data.data.tokenKey;
              var obj = {};
              obj.employee_name = that.ruleForm.employee_name; //名称

              obj.userkey = data.data.userKey;
              obj.tokenkey = data.data.tokenKey; //加密
              obj.password = aes.encrypt(
                that.ruleForm.password,
                data.data.tokenKey
              ); //密码
              obj.phone = that.ruleForm.phone; //电话
              obj.email = that.ruleForm.email; //邮箱
              obj.remark = that.ruleForm.remark; //评论
              obj.supplierCode = supplier[0].supplierCode; //供应商编码
              obj.supplierId = supplier[0].id; //供应商ID
              obj.ids = that.checkedCities; //授权角色
              obj.mainAccount = that.$global.user.userName; //主账号
              obj.creatorId = that.$global.user.id; //创建人ID
              obj.creator = that.$global.user.employeeName; //创建人
              obj.supplierCode = that.supplierInfo.supplierCode
                ? that.supplierInfo.supplierCode
                : "";
              obj.thirdPartyId = that.ruleForm.transport;
              that.btn_loading = true;
              _Api
                .addSup_user(obj)
                .then(function (response) {
                  var data = response.data;
                  that.btn_loading = false;
                  if (data.code == "1") {
                    that.$message({
                      message: "保存成功",
                      type: "success",
                    });
                    that.dialogVisible = false;
                    that.search(true);
                  } else {
                    that.disState = false;
                    that.$alert(data.info, {
                      showClose: false,
                      confirmButton: "确定",
                      customClass: "alertFailure",
                    });
                  }
                })
                .catch((err) => {
                  that.disState = false;
                  that.btn_loading = false;
                  that.$alert(err.data.message, {
                    showClose: false,
                    confirmButton: "确定",
                    customClass: "alertFailure",
                  });
                });
            }
          });
        });
      } else {
        this.$refs["ruleForm1"].validate((valid) => {
          if (valid == false) {
            return false;
          }
          this.disState = true;
          var that = this;
          var obj = {};
          obj.employee_name = this.ruleForm.employee_name;
          obj.phone = this.ruleForm.phone;
          obj.email = this.ruleForm.email;
          obj.remark = this.ruleForm.remark;
          obj.accountId = this.ruleForm.accountId;
          obj.isAdmin = this.ruleForm.isAdmin == 1 ? 1 : 0;
          that.btn_loading = true;
          _Api
            .editSup_user(obj)
            .then(function (response) {
              var data = response.data;
              that.btn_loading = false;
              if (data.code == "1") {
                that.$message({
                  message: "保存成功",
                  type: "success",
                });
                that.dialogVisible = false;
                var row = that.gridOptions.api.getSelectedRows();
                row[0].employee_name = obj.employee_name;
                row[0].email = obj.email;
                row[0].phone = obj.phone;
                row[0].remark = obj.remark;
                row[0].isAdmin = obj.isAdmin;
                that.gridOptions.api.refreshCells({force: true});
                // that.search();
              } else {
                that.disState = false;
                that.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              }
            })
            .catch((err) => {
              that.disState = false;
              that.btn_loading = false;
              that.$alert(err.data.message, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure",
              });
            });
        });
        //					editSup_user
      }
    },
    handleClose(done) {
      this.ruleForm = {};
      done();
    },
    handleCloseCcAccount() {
      this.ruleCcForm.ccAccount = "";
      this.ruleCcForm.employeeName = "";
      this.ruleCcForm.mobile = "";
      this.ruleCcForm.role = "";
      this.ruleCcForm.originalCCName = "";
      this.dialogCcVisible = false;
    },
    handleSaveCcAccount(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var row = this.gridOptions.api.getSelectedRows();

          let parmas = {
            accountId: row[0].accountId,
            roleName: this.getroleName,
          };

          this.$confirm("每个供应商最多只能开通10个CC账号，请谨慎操作！", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            distinguishCancelAndClose: true,
            customClass: "alertPrompt",
          }).then(() => {
            _Api
              .registerCc(parmas)
              .then((response) => {
                console.log(response, "response");
                let data = response.data;
                if (data.code == 1) {
                  this.$message({
                    message: data.info,
                    type: "success",
                  });
                  this.search();
                  this.dialogCcVisible = false;
                } else {
                  this.$message({
                    message: data.info,
                    type: "warning",
                  });
                }
              })
              .catch((err) => {
                this.$alert(err.data.message, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure",
                });
              });
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    handleCheckedCitiesChange(value) {
      this.checkedCities = value;
    },
    cancel2(type) {
      var that = this;
      this.$nextTick((_) => {
        that.$refs.ruleForm.clearValidate();
      });
      if (type == "push") {
        this.push_Vis = false;
      } else {
        this.addrole_Vis = false;
      }
    },
    //保存角色
    saveRole() {
      var that = this;

      var obj = {
        userIds: [],
        ids: [],
      };

      obj.userIds = [this.ruleForm.accountId];
      obj.ids = this.checkedCities; //userGroupId
      _Api.addRole(obj).then(function (response) {
        var data = response.data;
        if (data.code == "1") {
          that.$message({
            message: "保存成功",
            type: "success",
          });
          that.addrole_Vis = false;
          that.search();
        } else {
          that.$alert(data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure",
          });
        }
      });
    },
    // 开通CC账号
    openCCUser() {
      let localData = _utils.getSession("userData");

      var row = this.gridOptions.api.getSelectedRows();

      if (row.length <= 0) {
        this.$alert("提示：请选择一个想开通CC的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else if (row.length > 1) {
        this.$alert("提示：请只选择一个想开通CC的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
       
        this.ruleCcForm.ccAccount = row[0].username;
        this.ruleCcForm.employeeName = row[0].employee_name;
        this.ruleCcForm.mobile = row[0].phone;
        // let rowAuthUserGroupUsers = row[0].authUserGroupUsers;
        // rowAuthUserGroupUsers.forEach((item) => {
        //   this.ruleCcForm.role.push(item.userGroupId);
        // });
        this.ruleCcForm.originalCCName =
          localData.user.loginName +
          "__" +
          "角色" +
          "__" +
          row[0].employee_name;
      }
      this.dialogCcVisible = true;
    },
    // 改变用户角色
    changeUserRole(value) {
      let localData = _utils.getSession("userData");
      var row = this.gridOptions.api.getSelectedRows();
      this.roleCcList.map((item) => {
        if (item.code === value) {
          this.getroleName = item.name;
        }
      });

      this.ruleCcForm.originalCCName =
        localData.user.loginName +
        "__" +
        this.getroleName +
        "__" +
        row[0].employee_name;
    },
    //重置密码
    resetPwd() {
      var row = this.gridOptions.api.getSelectedRows();
      var that = this;
      if (row.length != 1) {
        that.$alert("提示：请选择一个帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else if (row[0].isAdmin != 1) {
        const { username, accountId } = row[0];
        waterfall(
          [
            function getTokeapin(callback) {
              _Api.getToken({ tokenkey: "get" }).then(
                function success(res) {
                  var data = res.data;
                  if (data.meta.code === 200) {
                    callback(null, data);
                  } else {
                    callback(res, 1);
                  }
                },
                function error(err) {
                  callback(err, 0);
                }
              );
            },
            function resetPassword(tokenData, callback) {
              var obj = {
                username: username,
                type: 1,
              };
              _Api.resetPassword(obj).then(
                function success(res) {
                  if (res.data.code == 1) {
                    that.$alert(" 重置成功,初始密码：111111 ", {
                      showClose: false,
                      confirmButtonText: "确定",
                      customClass: "alertSuccess",
                      callback: function () {},
                    });
                  } else {
                    callback(res, 2);
                  }
                },
                function error(err) {
                  callback(err, 3);
                }
              );
            },
          ],
          function (err, result) {
            let errMsg;
            switch (result) {
              case 0:
              case 1:
                errMsg = err.data.meta.msg;
                break;
              case 2:
                errMsg = "修改密码失败";
                break;
              case 3:
                errMsg = "修改密码失败，请检查网络";
                break;
            }
            that.$alert(errMsg, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertFailure",
            });
          }
        );
      }
    },
    // 推送设置
    pushSet() {
      let row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择一个想推送的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else if (row.length > 1) {
        this.$alert("提示：一次只能选择一个想推送的帐号！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt",
        });
        return;
      } else {
        this.tableData = [];
        this.ruleForm = row[0];
        this.getPushTypeList();
        this.push_Vis = true;
      }
    },
    // 保存推送信息
    savePush() {
      const { phone, username } = this.ruleForm;
      let isPush = this.tableData.some((item) => {
        return item.msgPush == true;
      });
      let codes = [];
      this.tableData.forEach((item) => {
        if (item.msgPush) {
          codes.push(item.busTypeCode);
        }
      });
      let params = {
        accountCode: username,
        busTypeCode: codes.join(","),
      };
      if (isPush) {
        if (!phone) {
          this.$message({
            message: "手机号不能为空，请先设置手机号!",
            type: "warning",
          });
          return;
        } else {
          this.btn_loading = true;
          _Api
            .savePushSetting(params)
            .then((res) => {
              let data = res.data;
              this.btn_loading = false;
              if (data.code == 1) {
                this.push_Vis = false;
                this.$message({
                  message: "推送设置成功",
                  type: "success",
                });
                this.search();
              } else {
                this.$alert(data.info, {
                  showClose: false,
                  confirmButtonText: "确定",
                  customClass: "alertFailure",
                });
              }
            })
            .catch((err) => {
              this.btn_loading = false;
              this.$alert(err.data.message, {
                showClose: false,
                confirmButtonText: "确定",
                customClass: "alertFailure",
              });
            });
        }
      } else {
        this.$confirm("你未设置任何推送信息是否确认保存？", "消息提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          distinguishCancelAndClose: true,
        })
          .then((_) => {
            this.btn_loading = true;
            _Api
              .savePushSetting(params)
              .then((res) => {
                let data = res.data;
                this.btn_loading = false;
                if (data.code == 1) {
                  this.push_Vis = false;
                  this.$message({
                    message: "推送设置成功",
                    type: "success",
                  });
                } else {
                  this.$alert(data.info, {
                    showClose: false,
                    confirmButtonText: "确定",
                    customClass: "alertFailure",
                  });
                }
              })
              .catch((err) => {
                this.btn_loading = false;
                this.$alert(err.data.message, {
                  showClose: false,
                  confirmButtonText: "确定",
                  customClass: "alertFailure",
                });
              });
          })
          .catch((_) => {
            console.log("已取消保存");
          });
      }
    },
    // 获取推送类型列表数据
    getPushTypeList() {
      const { username } = this.ruleForm;
      let params = {
        accountCode: username,
      };
      this.tab_loading = true;
      _Api
        .getPushUserList(params)
        .then((res) => {
          this.tab_loading = false;
          let data = res.data;
          if (data.code == 1) {
            this.tableData = data.rows;
          } else {
            this.$alert(data.info, {
              showClose: false,
              confirmButtonText: "确定",
              customClass: "alertFailure",
            });
          }
        })
        .catch((err) => {
          this.tab_loading = false;
          this.$alert(err.data.message, {
            showClose: false,
            confirmButtonText: "确定",
            customClass: "alertFailure",
          });
        });
    },
    selectTransport(rule, value, callback) {
      if ((!value || value == "") && this.showTransport) {
        callback(new Error("请选择运输方"));
      } else {
        callback();
      }
    },
    handleChangeTransport(value) {
      this.transportList.forEach((item) => {
        if (item.id == value) {
          this.ruleForm.employee_name = item.transportName;
        }
      });
    },
  },
  watch: {
    Sup_name(val) {
      if (val) this.current = 1;
      else this.current = this.currentPage;
    },
    checkedCities(val) {
      let selectRole = [];
      val.forEach((item) => {
        this.cities.forEach((cite) => {
          if (item == cite.id) {
            selectRole.push(cite.code);
          }
        });
      });
      if (selectRole.includes("srm_supplierSupervision_group")) {
        this.cities.forEach((item) => {
          if (item.code == "srm_supplierTransport_group") {
            this.$set(item, "disabled", true);
          } else {
            this.$set(item, "disabled", false);
          }
        });
      } else if (selectRole.includes("srm_supplierTransport_group")) {
        this.cities.forEach((item) => {
          if (item.code == "srm_supplierSupervision_group") {
            this.$set(item, "disabled", true);
          } else {
            this.$set(item, "disabled", false);
          }
        });
        this.showTransport = true;
        this.rules.transport[0].required = true;
      } else {
        this.cities.forEach((item) => {
          this.$set(item, "disabled", false);
        });
        this.showTransport = false;
        this.rules.transport[0].required = false;
        this.employeeNameReadonly = false;
        this.ruleForm.transport = "";
      }
    },
  },
  computed: {},
};
</script>

<style>
</style>